<template>
  <el-dialog
    class="pick-dialog"
    title="售后订单"
    :visible.sync="dialogVisible"
    :close-on-click-modal="false"
    width="1000px"
  >
    <div class="form-box" v-loading="loading">
      
      <div class="sale-info flex fbt">
        <div>
          <el-descriptions
            :labelStyle="{
              width: '100px',
            }"
            title="售后商品"
            labelClassName="label-txt"
            border
            :column="1"
          >
            <el-descriptions-item label="游戏名称">{{
              saleOrder.gameName
            }}</el-descriptions-item>
            <el-descriptions-item label="游戏账号">{{
              saleOrder.accountNumber
            }}</el-descriptions-item>
            <el-descriptions-item label="区服">{{
              saleOrder.qufu
            }}</el-descriptions-item>
            <el-descriptions-item label="商品编号">{{
              saleOrder.goodsId
            }}</el-descriptions-item>
            <el-descriptions-item label="平台售价">{{
              saleOrder.platformAmount
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <div>
          <el-descriptions
            :labelStyle="{
              width: '100px',
            }"
            title="买家信息"
            labelClassName="label-txt"
            border
            :column="1"
          >
            <el-descriptions-item label="买家名称">{{
              saleOrder.saleChannel
            }}</el-descriptions-item>
            <el-descriptions-item label="商品价格">{{
              saleOrder.platformAmount
            }}</el-descriptions-item>
            <!-- <el-descriptions-item label="优惠后金额">{{
              saleOrder.saleAmount
            }}</el-descriptions-item> -->
            <!-- <el-descriptions-item label="折扣比例">{{
              !saleOrder.saleDiscount || saleOrder.saleDiscount == "0.0"
                ? 10
                : saleOrder.saleDiscount
            }}</el-descriptions-item> -->
            <el-descriptions-item label="实付金额">{{
              saleOrder.actualAmount
            }}</el-descriptions-item>
            <el-descriptions-item label="支付状态">{{
              commonMaps.buyerPayState[saleOrder.salePay]
            }}</el-descriptions-item>
          </el-descriptions>
        </div>
        <!-- <div>
          <el-descriptions
            :labelStyle="{
              width: '110px',
            }"
            title="卖家信息"
            labelClassName="label-txt"
            border
            :column="1"
          >
            <el-descriptions-item label="卖家名称">{{
              saleOrder.supplyChannel
            }}</el-descriptions-item>
            <el-descriptions-item label="供货原价">{{
              saleOrder.supplyPlatformAmount
            }}</el-descriptions-item>
            <el-descriptions-item label="协商后供货价">{{
              saleOrder.supplyAmount
            }}</el-descriptions-item>

            <el-descriptions-item label="折扣比例">{{
              !saleOrder.supplyDiscount || saleOrder.supplyDiscount == "0.0"
                ? 10
                : saleOrder.supplyDiscount
            }}</el-descriptions-item>
            <el-descriptions-item label="结算金额">{{
              saleOrder.supplyDiscountAmount
            }}</el-descriptions-item>
            <el-descriptions-item label="平台佣金">{{
              Math.round(
                (saleOrder.supplyAmount - saleOrder.supplyDiscountAmount) * 100
              ) / 100
            }}</el-descriptions-item>
            <el-descriptions-item label="结算状态">
              <el-tag
                :type="
                  commonMaps.sellerPayState[saleOrder.supplySettlementState]
                    .type
                "
                >{{
                  commonMaps.sellerPayState[saleOrder.supplySettlementState]
                    .label || commonMaps.sellerPayState["1"].label
                }}</el-tag
              >
            </el-descriptions-item>
            <el-descriptions-item label="发货状态">{{
              commonMaps.sendStateMap[saleOrder.sendState]
            }}</el-descriptions-item>
          </el-descriptions>
        </div> -->
      </div>
      <el-descriptions
        title="售后信息"
        labelClassName="label-txt"
        border
        :column="3"
      >
        <el-descriptions-item label="售后编号">{{
          info.no
        }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{
          info.applicantName
        }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{
          info.applicantTime
        }}</el-descriptions-item>
        <el-descriptions-item label="退款类型">{{
          commonMaps.afterTypeMap[info.afterType]
        }}</el-descriptions-item>
        <el-descriptions-item label="退款金额">{{
          info.afterAmount
        }}</el-descriptions-item>
        <el-descriptions-item label="退款原因">{{
          info.afterReasonsName
        }}</el-descriptions-item>
        <el-descriptions-item label="退款说明" :span="3">
          {{ info.afterRemark }}
        </el-descriptions-item>
        <el-descriptions-item label="售后截图" :span="3">
          <div v-if="buyerImgs && buyerImgs.length">
            <el-image
              style="
                width: 80px;
                height: 80px;
                margin-right: 10px;
                margin-bottom: 10px;
              "
              :preview-src-list="buyerImgs"
              preview
              v-for="(img, i) in buyerImgs"
              :key="i"
              :src="img"
            ></el-image>
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <el-divider content-position="left">客服补充资料</el-divider>
      <!-- <h2 style="text-align:center">客服补充资料</h2> -->
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="auto"
        :rules="rules"
        class="demo-ruleForm"
      >
        <!-- <div>
          <b>
            <span>已退款金额:</span>
          </b>
        </div> -->
        <el-form-item v-if="sumAmount&&sumAmount>0" label="已退款金额:" >
          <b style="color:red">{{sumAmount}}元</b>
        </el-form-item>
        <el-form-item label="本次退款金额:" prop="platformPayAmount">
          <b style="color:red">{{ruleForm.platformPayAmount}}元</b>
          <!-- <el-input
            style="width: 250px"
            v-model="ruleForm.platformPayAmount"
            type="text"
            placeholder="请输入平台应退金额"
          ></el-input> -->
        </el-form-item>
        <el-form-item label="售后原因:" prop="realReasonsId">
          <el-select
            v-model="ruleForm.realReasonsId"
            placeholder="选择售后原因"
            style="width: 250px"
            filterable
            clearable
            @change="reasonChange"
          >
            <el-option
              v-for="(value, key) in afterReasons"
              :key="key"
              :label="value.dictLabel"
              :value="value.dictCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="违规类型:" prop="">
          <el-select v-model="violationRulesIds" multiple style="width: 250px">
            <el-option
              v-for="(item, i) in weiguiList"
              :key="i"
              :label="item.reason"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item> -->
        
        <!-- <el-form-item label="卖家应付:" prop="sellerPayAmount">
          <el-input
            style="width: 250px"
            v-model="ruleForm.sellerPayAmount"
            type="text"
            placeholder="请输入卖家应付金额"
          ></el-input>
        </el-form-item> -->
        <el-form-item label="补充描述:" prop="description">
          <el-input
            style="width: 600px"
            v-model="ruleForm.description"
            type="textarea"
            rows="5"
            placeholder="请输入售后补充描述..."
          ></el-input>
        </el-form-item>
        <el-form-item label="上传图片:" prop="afterImg">
          <el-upload
            :action="uploadImgUrl"
            list-type="picture-card"
            :file-list="imgShowList0"
            :multiple="true"
            :on-preview="handlePictureCardPreview"
            :on-success="handleUploadSuccess0"
            :on-remove="handleRemove0"
            :limit="9"
            :headers="headers"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>

      <div class="center">
        <el-button @click="submitForm('ruleForm', 'refuse')"
          >拒绝售后</el-button
        >
        <el-button
          type="primary"
          @click="submitForm('ruleForm', 'agree')"
          :loading="loading"
          >同意售后</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>

<script>
import orderAfterApi from "@/api/pickUp/afterSale.js";
import orderApi from "@/api/pickUp/order.js";
import { violationRulesList } from "@/api/weigui/index";
import { getToken } from "@/utils/auth";
export default {
  name: "afterOrderDone",
  data() {
    var priceRule = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入应付金额"));
      } else if (!this.priceReg.test(value)) {
        callback(new Error("请输入正确的金额"));
      } else {
        callback();
      }
    };
    return {
      dialogVisible: false,
      loading: false,
      info: "",
      infoArr: [],
      userInfo: {}, //当前登录人信息
      afterReasons: [],
      buyerImgs: [],
      ruleForm: {
        id: "",
        status: "",
        description: "",
        descriptionImg: "",
        platformPayAmount: "",
        sellerPayAmount: "",
        realReasonsId: "",
        realReasonsName: "",
      },
      rules: {
        realReasonsId: [
          { required: true, message: "请选择售后原因", trigger: "change" },
        ],
        platformPayAmount: [
          { required: true, message: "请输入应付金额", trigger: "blur" },
          { validator: priceRule, trigger: "blur" },
        ],
        sellerPayAmount: [
          { required: true, message: "请输入应付金额", trigger: "blur" },
          { validator: priceRule, trigger: "blur" },
        ],
      },
      // 上传相关
      uploadImgUrl: "",
      imgShowList0: [],
      newImages0: [],
      imgFileList0: [],
      saleOrder: {},
      weiguiList: [],
      violationRulesIds: [],
      headers:{},
      sumAmount:0,//已经售后的金额
    };
  },
  created() {
    this.uploadImgUrl = process.env.VUE_APP_BASE_API + "/upload/image";
    this.headers = {
      Authorization: "Bearer " + getToken(),
    };
  },
  methods: {
    open(info, flag) {
      this.imgShowList0=[],
      this.newImages0=[],
      this.sumAmount = 0
      this.ruleForm = {
        id: "",
        status: "",
        description: "",
        descriptionImg: "",
        platformPayAmount: "",
        sellerPayAmount: 0,
        realReasonsId: "",
        realReasonsName: "",
        violationRulesIds: "",
      };
      this.ruleForm.id = info.id;
      this.violationRulesIds = [];
      this.getReasons();
      this.getAfterOrderInfo(info.id);
      this.dialogVisible = true;
    },
    // 获取该订单已经售后的金额
    saleOrderAftesumAmount(saleOrderId){
      orderAfterApi.saleOrderAftesumAmount({
        saleOrderId:saleOrderId
      }).then(res=>{
        if(res.data.sumAmount){
          this.sumAmount = res.data.sumAmount
        }
      })
    },
    // 获取售后订单详情
    getAfterOrderInfo(id) {
      this.loading = true;
      this.buyerImgs = []
      orderAfterApi.saleOrderInfoById(id, { dataType: "all" }).then((res) => {
        this.info = res.data;
        this.ruleForm.platformPayAmount = this.info.afterAmount
        if (this.info.afterImg) {
          let imgs = [];
          let arr = JSON.parse(this.info.afterImg);
          arr.forEach((r) => {
            imgs.push(r.url);
          });
          this.buyerImgs = imgs;
        }
        this.saleOrderAftesumAmount(this.info.saleOrderId)
        this.getSaleOrderInfo();
      });
    },
    // 获取销售订单详情
    getSaleOrderInfo() {
      let obj = {
        id: this.info.saleOrderId,
        dataType: "all",
      };
      orderApi.orderPayStatusHandle(obj).then((res) => {
        this.saleOrder = res.data;
        this.loading = false;
      });
    },
    // 获取售后原因列表
    getReasons() {
      this.getDicts("realReasons").then((res) => {
        this.afterReasons = res.data;
      });
    },
    // 查询违规类型 violationRulesList
    getViolationRulesList() {
      violationRulesList({
        isPage: 2,
      }).then((res) => {
        this.weiguiList = res.rows;
      });
    },
    // 售后原因改变
    reasonChange(e) {
      if (e) {
        this.afterReasons.forEach((r) => {
          if (r.dictCode == e) {
            this.ruleForm.realReasonsName = r.dictLabel;
          }
        });
      }
      // this.ruleForm.afterReasonsName = this.commonMaps.afterReasonsMap[e]
    },
    afterAmountChange(e) {},
    // 点击提交按钮
    submitForm(formName, type) {
      if (type == "refuse") {
        this.submitFormSure(type);
      } else {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 判断金额是否超过订单实付
            let num =
              Number(this.ruleForm.platformPayAmount) +
              Number(this.ruleForm.sellerPayAmount);
            if (num != this.info.afterAmount) {
              return this.$message.error("总应付金额必须等于退款金额");
            }
            this.submitFormSure(type);
          } else {
            //console.log("error submit!!");
            return false;
          }
        });
      }
    },
    // 提交售后处理
    submitFormSure(type) {
      this.loading = true;
      // 组装图片附件
      // 拼接新上传的图片
      let ziliao = [];
      if (this["newImages0"] && this["newImages0"].length) {
        let newArr = [];
        this["newImages0"].forEach((img) => {
          newArr.push({
            name: img.name,
            url: img.response.data.filePath,
          });
        });
        ziliao = this["imgFileList0"].concat(newArr);
      } else {
        ziliao = this["imgFileList0"];
      }
      this.ruleForm.descriptionImg = JSON.stringify(ziliao);
      if (type == "refuse") {
        this.ruleForm.status = 2;
      } else if (type == "agree") {
        this.ruleForm.status = 1;
      }
      // if (this.violationRulesIds && this.violationRulesIds.length) {
      //   this.ruleForm.violationRulesIds = this.violationRulesIds.join(",");
      // } else {
      //   this.ruleForm.violationRulesIds = "";
      // }
      this.ruleForm.violationRulesIds = "";
      orderAfterApi
        .auditSaleAfterOrder(this.ruleForm)
        .then((res) => {
          this.loading = false;
          if (res.code == 200) {
            // 下单成功
            // // 跳转订单详情页面
            this.$message.success("售后处理成功");
            this.$parent.getList();
            this.close();
          }
        })
        .catch((err) => {
          this.loading = false;
        });
    },

    // 上传图片相关
    // 图片预览
    handlePictureCardPreview(file) {
      this.$viewerApi({
        images: [file.url],
      });
    },
    uploadNumber(file, fileList) {
      //限制图片数量
      this.$modal.msgError("最多只能上传9张图片");
    },
    // 图片上传成功
    handleUploadSuccess0(res, file, fileList) {
      if (res.code == 200) {
        // 取得新上传的文件
        this.newImages0 = fileList.filter((t) => {
          return t.url.indexOf("blob:") > -1;
        });
      }
    },
    // 图片删除
    handleRemove0(response) {
      const that = this;
      // 1.获取将要删除图片的临时路径
      const filePath = response.url;
      // 2.找到图片对应的索引值
      this.imgFileList0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.imgFileList0.splice(key, 1); //回显的图片
        }
      });
      this.newImages0.forEach(function (element, key) {
        if (element.url === filePath) {
          that.newImages0.splice(key, 1); //新上传的图片
        }
      });
    },
    close(formName) {
      this.dialogVisible = false;
    },
  },
};
</script>
<style scoped lang="scss">
.order-info {
  box-sizing: border-box;
  // height: 50px;
  background: #eee;
  padding: 15px;
  margin-bottom: 10px;
  flex-wrap: wrap;
  line-height: 26px;

  > span {
    margin-right: 20px;
  }
}
.form-box {
  
  .sale-info {
    width: 100%;
    align-content: space-between;
    margin-top: 20px;
    > div {
      width: 50%;
      margin-right: 15px;
    }
  }
}

.zdy-des {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 4;
  margin: 6px 0;
}

.demo-ruleForm {
  padding-right: 20px;
}

.center {
  text-align: right;
}



.pick-dialog >>> .el-input--medium input {
  text-align: left;
}
</style>
